

package com.yz.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yz.common.entity.TokenEntity;
import com.yz.common.entity.UserEntity;
import com.yz.common.entity.UserRoleEntity;
import com.yz.common.exception.RRException;
import com.yz.common.utils.ShiroUtils;
import com.yz.common.validator.Assert;
import com.yz.dao.TokenDao;
import com.yz.dao.UserDao;
import com.yz.form.LoginForm;
import com.yz.form.RegisterForm;
import com.yz.service.TokenService;
import com.yz.service.UserRoleService;
import com.yz.service.UserService;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
	@Autowired
	private TokenService tokenService;
	@Autowired
	private UserRoleService userRoleService;

	@Override
	public List<UserEntity> queryByMobile(String mobile) {
		UserEntity userEntity = new UserEntity();
		userEntity.setMobile(mobile);
		List<UserEntity> users = baseMapper.selectList(new EntityWrapper<UserEntity>().eq("username",mobile));
		if(users.size()==0){
			users.addAll(baseMapper.selectList(new EntityWrapper<UserEntity>().eq("mobile",mobile)));
		}
		return users;
	}

	@Override
	public Map<String, Object> login(LoginForm form) {
		List<UserEntity> user = queryByMobile(form.getMobile());
//		Assert.isNull(user, "手机号或密码错误");
		//密码错误
		if(user==null||user.size()==0||!passwdOK(form.getPassword(),user.get(0).getPassword(),user.get(0).getSalt())){
			throw new RRException("用户名或密码错误");
		}

		//获取登录token
		TokenEntity tokenEntity = tokenService.createToken(user.get(0).getUserId());

		Map<String, Object> map = new HashMap<>(2);
		map.put("token", tokenEntity.getToken());
		map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());

		return map;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean register(RegisterForm form) {
		List<UserEntity> users = this.baseMapper.selectList(new EntityWrapper<UserEntity>().eq("mobile",form.getMobile()));
	    if(users.size()!=0){
	    	return false;
		}else {
	    	UserEntity t = new UserEntity();
	    	t.setUsername(form.getMobile());
	    	t.setMobile(form.getMobile());
			String salt = RandomStringUtils.randomAlphanumeric(20);
	    	t.setSalt(salt);
	    	t.setPassword(ShiroUtils.sha256(form.getPassword(),salt));
	    	this.baseMapper.insert(t);

			List<UserEntity> user = this.baseMapper.selectList(new EntityWrapper<UserEntity>().eq("mobile",form.getMobile()));
			UserRoleEntity role = new UserRoleEntity();

			role.setUserId(user.get(0).getUserId());
			role.setRoleId(10);
	    	userRoleService.insert(role);
	    	return true;
		}
	}

	public static boolean passwdOK(String inputPasswd,String dbPasswd,String salt){
		MessageDigest digest = DigestUtils.getSha256Digest();
		if(salt!=null){
			digest.update(salt.getBytes());
		}
		byte[] rs = digest.digest(inputPasswd.getBytes());
		int iterations = 16 - 1;
		for (int i = 0; i < iterations; i++) {
			digest.reset();
			rs = digest.digest(rs);
		}

		String x = Hex.encodeHexString(rs);
		return StringUtils.equals(dbPasswd,x);
	}

}
